package com.plant.action;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.plant.entity.UgcCollect;
import com.plant.entity.UgcUser;
import com.plant.service.HelpService;
import com.plant.service.UserServic;
import com.plant.tool.DateUtils;
import com.plant.tool.HeadPhotoImageZipUtil;
@Controller                                                                     
@RequestMapping(value = "/user")                                                
public class UserAction {
	@Resource(name = "userInfoImlp")
	private UserServic userServic;

	@Resource(name = "helpServiceImpl")
	private HelpService helpService;

	@RequestMapping(value = "list")
	@ResponseBody                        
	public Map<String, Object> user(){ 
		Map<String, Object> map=new HashMap<String, Object>();
		System.out.println("你好我进接口了发福利 安抚");
		map.put("message", "查询成功");
		return map; 
	}


	@RequestMapping(value="friendsreq")//--1好友的请求列表接口
	@ResponseBody
	public List<Object> getByid(HttpServletResponse response,UgcUser user,String secret,String mdsc){
		response.setHeader("access-control-allow-origin","*");
		Map<Object,Object> map=new HashMap<Object, Object>();
		List<Object> list1=new ArrayList<Object>();
		if(mdsc==null||secret==null||user.getId()==null){
			map.put("message", "参数错误");
			map.put("state", 0);
			list1.add(map);
			return list1;
		}else{
			Md md=new Md();
			String mds=md.md5calc(secret+"flower_duigu2016");
			if(mdsc.endsWith(mds)){
				List<Object[]> list=new ArrayList<Object[]>();
				list=userServic.friendreq(user);
				for (int i = 0; i < list.size(); i++) {
					Map<Object,Object> map1=new HashMap<Object, Object>();
					Object[] obj=list.get(i);
					Integer sta=(Integer) obj[3];
					if(sta==0||sta==1){
						map1.put("id", obj[0]);
						map1.put("nickname", obj[1]);
						map1.put("photo", obj[2]);
						map1.put("state", obj[3]);
						map1.put("user_id", obj[4]);
						list1.add(map1);
					}
				}
				return list1;
			}else{
				String error="秘钥错误";
				list1.add(error);
				return list1;
			}
		}
	}


	@RequestMapping(value="newcollect")//2新建用户收藏
	@ResponseBody
	public Map<String, Object> NewCollect(HttpServletRequest request,UgcCollect uc,Integer user_id,
			Integer content_id,Integer content_type,String secret,String pust_val){
		Map<String,Object> map=new HashMap<String, Object>();
		if(pust_val==null||secret==null){
			map.put("message", "参数错误");
			map.put("state", "0");
			return map;
		}else{
			Md md=new Md();
			String mds=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mds)){
				uc.setContentId(content_id);
				uc.setContentType(content_type);//content_type 1为文章 2为话题
				uc.setUserId(user_id);
				SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String t=sim.format(new Date());
				String ip=GetIp.getip(request);
				uc.setCreateTime(Timestamp.valueOf(t));
				uc.setIp(ip);
				boolean b=userServic.AddUserCollect(uc);
				if(b){
					map.put("message", "收藏成功");
					map.put("state", "1");
				}else{
					map.put("message", "收藏失败");
					map.put("state", "0");
				}
				return map;
			}else{
				map.put("message", "秘钥错误");
				map.put("state", "0");
				return map;
			}
		}
	}


	@RequestMapping(value ="oneuser")//--2.查找 单个用户的资料
	@ResponseBody
	public List<Object> oneUser(HttpServletResponse response,UgcUser user,String secret,String mdsc){
		response.setHeader("access-control-allow-origin","*");
		List<Object> list=new ArrayList<Object>();
		if(user.getId()==null||secret==null||mdsc==null){
			String error="输入信息不能为空";
			list.add(error);
			return list;
		}else{
			Md md=new Md();
			String mds=md.md5calc(secret+"flower_duigu2016");
			if(mdsc.endsWith(mds)){
				return userServic.getByuid(user);
			}else{
				String error="秘钥错误";
				list.add(error);
				return list;
			}
		}
	}


	
	@RequestMapping(value ="oneuserinf")//---3.查询单个用户详情 包括朋友关系
	@ResponseBody
	public Map<Object,Object> oneUserinf(HttpServletResponse response,UgcUser user,String secret,String mdsc,Integer uid){
		response.setHeader("access-control-allow-origin","*");
		Map<Object, Object> map=new HashMap<Object, Object>();
		if(user.getId()==null||secret==null||mdsc==null||uid==null){
			map.put("message", "传参错误");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mds=md.md5calc(secret+"flower_duigu2016");
			if(mdsc.endsWith(mds)){
				Integer rid=user.getId();
				List<Object> list=new ArrayList<Object>();
				list=userServic.getByuid(user);
				List<Object> list1=new ArrayList<Object>();
				List<Object> list2=new ArrayList<Object>();
				list1=userServic.isfriend(uid, rid);
				list2=userServic.IsNotfriend(uid, rid);
				if(list1.size()==0&&list2.size()==0){
					map.put("isfriend",0);
				}else{
					map.put("isfriend", 1);
				}
				map.put("user", list);
				map.put("message", "查询成功");
				map.put("state", 1);
				return map;
			}else{
				map.put("message", "秘钥错误");
				map.put("state", 0);
				return map;
			}
		}
	}
	
	@RequestMapping(value ="remind_who")//---提醒谁看
	@ResponseBody
	public Map<Object,Object> RemindWho(Integer user_id,UgcUser u,HttpServletResponse response,String secret,String pust_val){
		response.setHeader("access-control-allow-origin","*");
		Map<Object, Object> map=new HashMap<Object, Object>();
		if(secret==null||pust_val==null||user_id==null){
			map.put("message", "传参错误");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mds=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mds)){
				u.setId(user_id);
				List<Object> content=new ArrayList<Object>();
				List<Object[]> list=new ArrayList<Object[]>();
				List<Object> list3=new ArrayList<Object>();
				List<Object> list2=new ArrayList<Object>();
				list2=helpService.GetFriendUidByA(u);
				list3=helpService.GetFriendUidByR(u);
				list3.addAll(list2);
				int len=list3.size();
				if(len>0){
					Object ids=StringUtils.join(list3.toArray(),",");
					list=userServic.UserThreeInf(ids);
					for (int i = 0; i < list.size(); i++) {
						Map<Object,Object> map1=new HashMap<Object, Object>();
						Object[] obj=list.get(i);
						map1.put("user_id", obj[0]);
						map1.put("nickname", obj[1]);
						map1.put("user_photo", obj[2]);
						content.add(map1);
					}
					map.put("content", content);
				}
				map.put("message", "查询成功");
				map.put("state", 1);
				return map;
			}else{
				map.put("message", "秘钥错误");
				map.put("state", 0);
				return map;
			}
		}
	}


	@RequestMapping(value ="mylanmu")//----4..我的栏目
	@ResponseBody
	public Map<Object,Object> lanmu(HttpServletResponse response,UgcUser user,String secret,String mdsc){//----4.我的的栏目接口
		response.setHeader("access-control-allow-origin","*");
		List<Object> list2=new ArrayList<Object>();
		Map<Object,Object> map=new HashMap<Object,Object>();
		if(user.getId()==null||secret==null||mdsc==null){
			map.put("error", "请查看参数是否正确");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mds=md.md5calc(secret+"flower_duigu2016");
			if(mdsc.endsWith(mds)){
				list2=userServic.getByuid(user);
				long l=userServic.myfriendcount(user);
				map.put("friendcount",l);
				map.put("userinf",list2);
				map.put("message", "请求我的栏目成功");
				return map;
			}else{
				map.put("error", "秘钥错误");
				map.put("state", 1);
				return map;
			}
		}
	}

	@RequestMapping(value ="my_moment")//----5.我的个人动态
	@ResponseBody
	public Map<Object,Object> MyMoment(Integer page,String first_page_time,Integer user_id,UgcUser uf,HttpServletResponse response,UgcUser user,String secret,String pust_val){
		response.setHeader("access-control-allow-origin","*");
		Map<Object,Object> map=new HashMap<Object,Object>();
		if(secret==null||pust_val==null||page==null||first_page_time==null){
			map.put("message", "请查看参数是否正确");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mds=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mds)){
				List<Object[]> list=new ArrayList<Object[]>();
				List<Object[]> list4=new ArrayList<Object[]>();
				List<Object[]> list2=new ArrayList<Object[]>();
				List<Object[]> list3=new ArrayList<Object[]>();
				List<Object> list1=new ArrayList<Object>();
				Integer p=(page-1)*10;
				uf.setId(user_id);
				SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				DateUtils du=new DateUtils();
				list=userServic.MyMoment(uf, first_page_time,p);
				list4=userServic.MyMoment(uf, first_page_time,p+1);
				if(list4.size()>0){
					map.put("hasmore", 1);
				}else{
					map.put("hasmore", 0);
				}
				for (int i = 0; i < list.size(); i++) {
					Map<Object,Object> map1=new HashMap<Object,Object>();
					Object[] obj=list.get(i);
					Integer content_type=Integer.parseInt(obj[4].toString());
					if(content_type==1){
						map1.put("id_key", obj[0]);
						String t=sim.format(obj[2]);
						long l=du.getUnixStamps(t);
						map1.put("date",du.TopicCommentTime(l));
						map1.put("content_type", obj[4]);
						map1.put("label", "上传照片");
						map1.put("content", obj[3]);
						map1.put("images_list", userServic.NewThingsImages(obj[0]));
						list1.add(map1);
					}
					if(content_type==3){
						List<Object> image=new ArrayList<Object>();
						map1.put("id_key", obj[0]);
						String t=sim.format(obj[2]);
						long l=du.getUnixStamps(t);
						map1.put("date",du.TopicCommentTime(l));
						map1.put("content_type", obj[4]);
						map1.put("label", "发出求助");
						map1.put("content", obj[3]);
						image=userServic.FaqImage(obj[0]);
						String images=null;
						for (int j = 0; j < image.size(); j++) {
							images=String.valueOf(image.get(j));
						}
						map1.put("image",images);
						map1.put("answer_count", userServic.FaqCountBid(obj[0]));
						list1.add(map1);
					}
					if(content_type==4){
						map1.put("id_key", obj[0]);
						String t=sim.format(obj[2]);
						long l=du.getUnixStamps(t);
						map1.put("date",du.TopicCommentTime(l));
						map1.put("content_type", obj[4]);
						map1.put("label", "讨论话题");
						map1.put("content", obj[3]);
						List<Object> imagelist=new ArrayList<Object>();
						imagelist=userServic.TopicJoinImages(uf,obj[0]);
						map1.put("images_list",imagelist);

						uf.setId(Integer.parseInt(obj[1].toString()));
						list3=userServic.TopicJoinInf(uf, obj[0]);
						if(list3.size()==0){
							map1.put("to_topic_s_id", "");
							map1.put("to_topic_s_title", "");
							map1.put("to_topic_s_joined_people_count", "");
						}else{
							for (int j = 0; j < list3.size(); j++) {
								Object[] obj3=list3.get(j);
								map1.put("to_topic_s_id", obj3[0]);
								map1.put("to_topic_s_title", obj3[1]);
								map1.put("to_topic_s_joined_people_count", userServic.TopicJoinCountBid(obj3[0]));
							}
						}
						list1.add(map1);
					}
					if(content_type==5){
						map1.put("id_key", obj[0]);
						String t=sim.format(obj[2]);
						long l=du.getUnixStamps(t);
						map1.put("date",du.TopicCommentTime(l));
						map1.put("content_type", obj[4]);
						map1.put("label", "回答求助");
						map1.put("content", obj[3]);
						UgcUser u=new UgcUser();
						u.setId(Integer.parseInt(obj[1].toString()));
						list2=userServic.FaqInf(u, obj[0]);
						if(list2.size()==0){
							map1.put("to_faq_s_id","");	
							map1.put("to_faq_s_title","");	
							map1.put("image", "");
							map1.put("to_faq_s_answer_count","");
						}else{
							List<Object> image=new ArrayList<Object>();
							for (int j = 0; j <list2.size(); j++) {
								Object[] obj2=list2.get(j);
								map1.put("to_faq_s_id",obj2[0]);	
								map1.put("to_faq_s_title",obj2[1]);	
								image=userServic.FaqImage(obj2[0]);
								String images=null;
								for (int k = 0; k < image.size(); k++) {
									images=String.valueOf(image.get(k));
								}
								map1.put("image",images);
								map1.put("to_faq_s_answer_count", userServic.FaqCountBid(obj2[0]));
							}
						}
						list1.add(map1);
					}
				}
				map.put("timeline", list1);
				map.put("message", "ok");
				map.put("state", 1);
				return map;
			}else{
				map.put("error", "秘钥错误");
				map.put("state", 1);
				return map;
			}
		}
	}


	@RequestMapping(value ="testmy_moment")//----5.我的个人动态
	@ResponseBody
	public Map<String,Object> TestMyMoment(Integer page,String first_page_time,Integer user_id,
			UgcUser uf,HttpServletResponse response,UgcUser user,String secret,String pust_val){
		response.setHeader("access-control-allow-origin","*");
		Map<String,Object> map=new HashMap<String,Object>();
		//    	if(secret==null||pust_val==null||page==null||first_page_time==null){
		//    		map.put("message", "请查看参数是否正确");
		//    		map.put("state", 0);
		//    		return map;
		//    	}else{
		//    		Md md=new Md();
		//    		String mds=md.md5calc(pust_val+"flower_duigu2016");
		//    		if(secret.endsWith(mds)){
		List<Map<String,Object>> templist=new ArrayList<Map<String,Object>>();
		String querytime="2016-11-29 19:11:36";
		uf.setId(35);
		Integer p=(1-1)*10;
		Map<String, Object> typemap=new HashMap<String, Object>();
		typemap.put("1", "发布新鲜事");
		typemap.put("3", "发出求助");
		typemap.put("4", "讨论话题");
		typemap.put("5", "回答求助");
		templist=userServic.LanMuMyMoment(uf, querytime, p);
		for (Map<String, Object> map2 : templist) {
			Timestamp time=(Timestamp) map2.get("create_time");
			String temptime=DateUtils.timeStamp(time.getTime());
			map2.remove("create_time");
			map2.put("create_time", temptime);
		}
		for (Map<String, Object> temp : templist) {
			String type=String.valueOf(temp.get("content_type"));
			temp.put("label", typemap.get(type));
			if(type.equals("1")){
				Object obj=temp.get("id_key");
				temp.put("images_list",userServic.NewThingsImages(obj));
			}
		}
		map.put("timeline",templist);
		return map;
		//    		}else{
		//    			map.put("error", "秘钥错误");
		//    			map.put("state", 1);
		//    			return map;
		//    		}
		//    	}
	}

	/**我的个人动态按日期分组显示
	 * @param page
	 * @param first_page_time
	 * @param user_id
	 * @param secret
	 * @param pust_val
	 * @return
	 */
	@RequestMapping(value = "my_moment_group_by_day")
	@ResponseBody
	public Map<String, Object> MyMomentGroupByDay(Integer page,
			String first_page_time, Integer user_id, UgcUser uf,
			HttpServletResponse response, UgcUser user, String secret,
			String pust_val) {
		Map<String, Object> result = new HashMap<String, Object>();
		response.setHeader("access-control-allow-origin", "*");
		if(secret==null||pust_val==null||page==null||first_page_time==null){
			result.put("message", "请查看参数是否正确");
			result.put("state", 0);
			return result;
		}else{
			Md md=new Md();
			String mds=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mds)){
				//    			uf.setId(144);
				//    			String qurryTime = "2016-11-29 19:11:36";
				uf.setId(user_id);
				Integer p = (page-1) * 10;
				Map<String, String> typeMap = new HashMap<String, String>();//
				typeMap.put("1", "上传照片");
				typeMap.put("3", "发出求助");
				typeMap.put("4", "讨论话题");
				typeMap.put("5", "回答求助");
				List<Map<String, Object>> tempList = new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> list4 = new ArrayList<Map<String, Object>>();
				System.out.println("ppp"+p);
				tempList = userServic.LanMuMyMoment(uf, first_page_time, p);
				list4 = userServic.LanMuMyMoment(uf, first_page_time, p+1);
				int hasmore = 0;
				if (list4.size()> 0) {
					hasmore = 1;
				}
				Map<String, List<Map<String, Object>>> temp=new LinkedHashMap<String, List<Map<String,Object>>>();//
				for (Map<String, Object> tempMap : tempList) {
					Timestamp time1 = (Timestamp) tempMap.get("create_time");//通过键值    获取时间
					String tempTime = DateUtils.timeStamp(time1.getTime());
					if (temp.containsKey(tempTime)) {
						temp.get(tempTime).add(tempMap);
					}else{
						List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
						list.add(tempMap);
						temp.put(tempTime, list);
					}
				}
				List<Map<String, Object>> timelines = new ArrayList<Map<String, Object>>();
				for (String time : temp.keySet()) {
					Map<String, Object> timeline = new HashMap<String, Object>();
					List<Map<String, Object>> timeList = temp.get(time);
					for (Map<String, Object> map : timeList) {
						String type = String.valueOf(map.get("content_type"));
						map.put("label", typeMap.get(type));
						if (type.equals("1")) {
							Object obj=map.get("id_key");
							map.put("images_list", userServic.NewThingsImages(obj));
						}
						if (type.equals("3")) {
							Object obj=map.get("id_key");
							map.put("images_list", userServic.FaqImage(obj));
							map.put("answer_count", userServic.FaqCountBid(obj));
						}
						if (type.equals("4")) {
							Map<String, Object> discuss=new HashMap<String, Object>();
							List<Object[]> list3=new ArrayList<Object[]>();
							Object obj=map.get("id_key");
							List<Object> imagelist=new ArrayList<Object>();
							imagelist=userServic.TopicJoinImages(uf,obj);
							map.put("images_list",imagelist);
							list3=userServic.TopicJoinInf(uf, obj);
							if(list3.size()==0){
								discuss.put("to_topic_s_id", "");
								discuss.put("to_topic_s_title", "");
								discuss.put("to_topic_s_joined_people_count", "");
							}else{
								for (int j = 0; j < list3.size(); j++) {
									Object[] obj3=list3.get(j);
									discuss.put("id_key", obj3[0]);
									discuss.put("title", obj3[1]);
									discuss.put("joined_people_count", userServic.TopicJoinCountBid(obj3[0]));
								}
								map.put("to_topic", discuss);
							}
						}
						if (type.equals("5")) {
							Map<String, Object> discuss5=new HashMap<String, Object>();
							List<Object[]> list2=new ArrayList<Object[]>();
							Object obj=map.get("id_key");
							list2=userServic.FaqInf(uf,obj);
							if(list2.size()==0){
								discuss5.put("id_key","");	
								discuss5.put("title","");	
								discuss5.put("image", "");
								discuss5.put("answer_count","");
							}else{
								for (int j = 0; j <list2.size(); j++) {
									List<Object> image=new ArrayList<Object>();
									Object[] obj2=list2.get(j);
									discuss5.put("id_key",obj2[0]);	
									discuss5.put("title",obj2[1]);
									image=userServic.FaqImage(obj2[0]);
									for (int i = 0; i < image.size(); i++) {
										discuss5.put("image",image.get(i).toString());
									}
									discuss5.put("answer_count", userServic.FaqCountBid(obj2[0]));
								}
							}
							map.put("to_faq", discuss5);
						}
						map.remove("create_time");
						map.remove("user_id");
					}
					timeline.put("day", time);
					timeline.put("list", timeList);
					timelines.add(timeline);
				}
				result.put("hasmore", hasmore);
				result.put("timeline", timelines);
				return result;
			}else{
				result.put("error", "秘钥错误");
				result.put("state", 1);
				return result;
			}
		}
	}



	@RequestMapping(value="updateU")  //--6修改用户基本资料接口
	@ResponseBody
	public List<Object> updateU(HttpServletResponse response,UgcUser user,String secret,String mdsc,HttpServletRequest request,@RequestParam(value = "file", required = false) MultipartFile[] myfiles,ModelMap model) throws IOException, FileUploadException{
		response.setHeader("access-control-allow-origin","*");
		List<Object> list=new ArrayList<Object>();
		Md md=new Md();
		String mdc=md.md5calc(secret+"flower_duigu2016");
		if(secret==null||mdsc==null||user.getId()==null){
			String error="秘钥或是用户id为空";	
			list.add(error);
			return list;
		}else{
			if(mdsc.endsWith(mdc)){
				UgcUser u=new UgcUser();
				u=(UgcUser) userServic.OneUser(user);//----查询单个用户信息
				GetIp getip=new GetIp();//1.获得的IP
				String ip=getip.getIp2(request);
				String photoName=null;
				System.out.println("开始上传");  
				for(MultipartFile myfile : myfiles){  
					if(myfile.isEmpty()){  
						System.out.println("文件未上传");
						return null;
					}else{  
						System.out.println("文件长度: " + myfile.getSize());  
						System.out.println("文件类型: " + myfile.getContentType());  
						System.out.println("文件名称: " + myfile.getName());  
						System.out.println("文件原名: " + myfile.getOriginalFilename());  
						System.out.println("========================================");  
						String fileName=myfile.getOriginalFilename();
						fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
						String extName = fileName.substring(fileName.lastIndexOf("."));//.jpg
						String uuid = UUID.randomUUID().toString().replace("-", "");
						String newName = uuid+extName;   
						String realPath = request.getSession().getServletContext().getInitParameter("UPLOAD_IMAGE_PATH");//从配置文件中读取要保存的位置 
						org.apache.commons.io.FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath,newName));  
						photoName="http://www.zhiwuxiansheng.com:8080/images/HeadPhoto/"+newName;
						HeadPhotoImageZipUtil img=new HeadPhotoImageZipUtil();
						img.zipImageFile(new File(realPath,newName), new File(realPath,newName), 640, 640, 0.6f);
					}  
				}  
				SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String t=sim.format(new Date());
				user.setLevel(u.getLevel());
				user.setPassword(u.getPassword());
				user.setTel(u.getTel());
				user.setRegisterTime(Timestamp.valueOf(t));//2.添加用户注册时间
				user.setPhoto(photoName);				   //3.获取上传图片的名字
				user.setIp(ip);
				user.setMyId(u.getMyId());
				user.setDiviceToken(u.getDiviceToken());
				userServic.updateU(user);
				return userServic.getByuid(user); //--返回显示用户修改后的资料
			}else{
				String error="接口秘钥不对";	
				list.add(error);
				return list;
			}
		}
	}
}
